<template>
  <div class="admin-task-edit">
    <div class="page-header">
      <h2>{{ isEdit ? '编辑任务' : '新建任务' }}</h2>
      <div class="header-actions">
        <button class="admin-btn" @click="goBack">返回列表</button>
        <button class="admin-btn admin-btn-primary" @click="saveTask">保存</button>
      </div>
    </div>
    
    <div class="loading-container" v-if="loading">
      <div class="loading-spinner"></div>
      <p>{{ isEdit ? '正在加载任务详情...' : '准备创建任务...' }}</p>
    </div>
    
    <div class="error-container" v-else-if="error">
      <div class="error-icon">❌</div>
      <h3>出错了</h3>
      <p>{{ error }}</p>
      <button class="admin-btn" @click="goBack">返回列表</button>
    </div>
    
    <div class="edit-form-container" v-else>
      <div class="admin-alert admin-alert-info" v-if="isEdit">
        <p>当前正在编辑ID为 <strong>{{ taskId }}</strong> 的任务。</p>
      </div>
      
      <div class="admin-form edit-form">
        <div class="form-section">
          <h3 class="section-title">基本信息</h3>
          
          <div class="form-row">
            <div class="admin-form-item">
              <label class="admin-form-label required">任务名称</label>
              <input
                type="text"
                v-model="formData.title"
                class="admin-form-input"
                placeholder="请输入任务名称"
              >
              <div class="admin-form-error" v-if="errors.title">{{ errors.title }}</div>
            </div>
          </div>
          
          <div class="form-row two-col">
            <div class="admin-form-item">
              <label class="admin-form-label required">所属挑战</label>
              <select v-model="formData.challengeId" class="admin-form-input">
                <option value="">请选择挑战</option>
                <option v-for="challenge in challenges" :key="challenge.id" :value="challenge.id">
                  {{ challenge.title }}
                </option>
              </select>
              <div class="admin-form-error" v-if="errors.challengeId">{{ errors.challengeId }}</div>
            </div>
            
            <div class="admin-form-item">
              <label class="admin-form-label required">完成类型</label>
              <select v-model="formData.taskType" class="admin-form-input">
                <option value="">请选择类型</option>
                <option value="daily">每日任务</option>
                <option value="weekly">每周任务</option>
                <option value="one_time">一次性任务</option>
              </select>
              <div class="admin-form-error" v-if="errors.taskType">{{ errors.taskType }}</div>
            </div>
          </div>
          
          <div class="form-row two-col">
            <div class="admin-form-item">
              <label class="admin-form-label required">开始时间</label>
              <input
                type="date"
                v-model="formData.startTime"
                class="admin-form-input"
              >
              <div class="admin-form-error" v-if="errors.startTime">{{ errors.startTime }}</div>
            </div>
            
            <div class="admin-form-item">
              <label class="admin-form-label required">结束时间</label>
              <input
                type="date"
                v-model="formData.endTime"
                class="admin-form-input"
              >
              <div class="admin-form-error" v-if="errors.endTime">{{ errors.endTime }}</div>
            </div>
          </div>
          
          <div class="form-row">
            <div class="admin-form-item">
              <label class="admin-form-label required">任务描述</label>
              <textarea
                v-model="formData.description"
                class="admin-form-input"
                placeholder="请输入任务描述"
                rows="4"
              ></textarea>
              <div class="admin-form-error" v-if="errors.description">{{ errors.description }}</div>
            </div>
          </div>
        </div>
        
        <div class="form-section">
          <h3 class="section-title">完成条件</h3>
          
          <div class="form-row two-col">
            <div class="admin-form-item">
              <label class="admin-form-label required">提交方式</label>
              <div class="submission-types">
                <label class="submission-type">
                  <input 
                    type="checkbox" 
                    v-model="formData.submissionTypes.text"
                  >
                  <span>文字描述</span>
                </label>
                
                <label class="submission-type">
                  <input 
                    type="checkbox" 
                    v-model="formData.submissionTypes.image"
                  >
                  <span>图片上传</span>
                </label>
                
                <label class="submission-type">
                  <input 
                    type="checkbox" 
                    v-model="formData.submissionTypes.location"
                  >
                  <span>位置信息</span>
                </label>
              </div>
              <div class="admin-form-error" v-if="errors.submissionTypes">{{ errors.submissionTypes }}</div>
            </div>
            
            <div class="admin-form-item">
              <label class="admin-form-label">图片要求</label>
              <div class="image-requirements" v-if="formData.submissionTypes.image">
                <div class="req-item">
                  <label>最小图片数:</label>
                  <input
                    type="number"
                    v-model.number="formData.imageRequirements.minCount"
                    class="admin-form-input small-input"
                    min="0"
                  >
                </div>
                
                <div class="req-item">
                  <label>最大图片数:</label>
                  <input
                    type="number"
                    v-model.number="formData.imageRequirements.maxCount"
                    class="admin-form-input small-input"
                    min="1"
                  >
                </div>
              </div>
              <div class="admin-form-helper" v-if="formData.submissionTypes.image">
                设置用户提交时需要上传的图片数量限制
              </div>
              <div class="disabled-message" v-else>
                请先选择"图片上传"提交方式
              </div>
            </div>
          </div>
          
          <div class="form-row">
            <div class="admin-form-item">
              <label class="admin-form-label">文字要求</label>
              <div class="text-requirements" v-if="formData.submissionTypes.text">
                <div class="req-item">
                  <label>最小字数:</label>
                  <input
                    type="number"
                    v-model.number="formData.textRequirements.minLength"
                    class="admin-form-input small-input"
                    min="0"
                  >
                </div>
                
                <div class="req-item">
                  <label>最大字数:</label>
                  <input
                    type="number"
                    v-model.number="formData.textRequirements.maxLength"
                    class="admin-form-input small-input"
                    min="1"
                  >
                </div>
              </div>
              <div class="admin-form-helper" v-if="formData.submissionTypes.text">
                设置用户提交文字描述的字数限制
              </div>
              <div class="disabled-message" v-else>
                请先选择"文字描述"提交方式
              </div>
            </div>
          </div>
          
          <div class="form-row">
            <div class="admin-form-item">
              <label class="admin-form-label">审核规则</label>
              <div class="review-options">
                <label class="review-option">
                  <input 
                    type="radio" 
                    v-model="formData.reviewType" 
                    value="auto"
                  >
                  <div class="option-info">
                    <span class="option-title">自动审核</span>
                    <span class="option-desc">系统自动通过用户提交的任务</span>
                  </div>
                </label>
                
                <label class="review-option">
                  <input 
                    type="radio" 
                    v-model="formData.reviewType" 
                    value="manual"
                  >
                  <div class="option-info">
                    <span class="option-title">人工审核</span>
                    <span class="option-desc">管理员需要手动审核用户提交的任务</span>
                  </div>
                </label>
              </div>
            </div>
          </div>
        </div>
        
        <div class="form-section">
          <h3 class="section-title">奖励设置</h3>
          
          <div class="form-row two-col">
            <div class="admin-form-item">
              <label class="admin-form-label required">积分奖励</label>
              <input
                type="number"
                v-model.number="formData.points"
                class="admin-form-input"
                min="0"
                placeholder="完成任务获得的积分"
              >
              <div class="admin-form-error" v-if="errors.points">{{ errors.points }}</div>
            </div>
            
            <div class="admin-form-item">
              <label class="admin-form-label">额外奖励</label>
              <select v-model="formData.extraReward" class="admin-form-input">
                <option value="">无额外奖励</option>
                <option value="badge">徽章</option>
                <option value="coupon">优惠券</option>
                <option value="experience">经验值</option>
              </select>
            </div>
          </div>
          
          <div class="form-row" v-if="formData.extraReward">
            <div class="admin-form-item">
              <label class="admin-form-label">额外奖励详情</label>
              <textarea
                v-model="formData.extraRewardDetails"
                class="admin-form-input"
                placeholder="请输入额外奖励的详细说明"
                rows="3"
              ></textarea>
            </div>
          </div>
        </div>
        
        <div class="form-section">
          <h3 class="section-title">高级设置</h3>
          
          <div class="form-row">
            <div class="admin-form-item">
              <label class="admin-form-label">任务状态</label>
              <div class="status-options">
                <label class="status-option">
                  <input type="radio" v-model="formData.status" value="upcoming">
                  <span class="status-label">即将开始</span>
                </label>
                
                <label class="status-option">
                  <input type="radio" v-model="formData.status" value="active">
                  <span class="status-label">进行中</span>
                </label>
                
                <label class="status-option">
                  <input type="radio" v-model="formData.status" value="completed">
                  <span class="status-label">已完成</span>
                </label>
                
                <label class="status-option">
                  <input type="radio" v-model="formData.status" value="expired">
                  <span class="status-label">已过期</span>
                </label>
              </div>
            </div>
          </div>
          
          <div class="form-row">
            <div class="admin-form-item">
              <label class="admin-form-label">优先级</label>
              <div class="priority-slider">
                <input
                  type="range"
                  v-model.number="formData.priority"
                  min="1"
                  max="5"
                  step="1"
                  class="slider"
                >
                <div class="priority-labels">
                  <span>低</span>
                  <span>中</span>
                  <span>高</span>
                </div>
              </div>
              <div class="priority-value">当前优先级: {{ getPriorityText(formData.priority) }}</div>
            </div>
          </div>
          
          <div class="form-row">
            <div class="admin-form-item">
              <label class="admin-form-label">其他设置</label>
              <div class="other-settings">
                <label class="setting-item">
                  <input type="checkbox" v-model="formData.settings.featured">
                  <span>推荐任务</span>
                </label>
                
                <label class="setting-item">
                  <input type="checkbox" v-model="formData.settings.repeatable">
                  <span>可重复完成</span>
                </label>
                
                <label class="setting-item">
                  <input type="checkbox" v-model="formData.settings.requireVerification">
                  <span>需要验证码</span>
                </label>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <div class="form-actions">
        <button class="admin-btn" @click="goBack">取消</button>
        <button 
          class="admin-btn admin-btn-danger" 
          v-if="isEdit"
          @click="confirmDeleteTask"
        >
          删除任务
        </button>
        <button class="admin-btn admin-btn-primary" @click="saveTask">保存任务</button>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'AdminTaskEdit',
  data() {
    return {
      taskId: this.$route.params.id,
      isEdit: !!this.$route.params.id,
      loading: false,
      error: null,
      challenges: [
        { id: 1, title: '低碳生活挑战' },
        { id: 2, title: '节能减排计划' },
        { id: 3, title: '垃圾分类达人' }
      ],
      formData: {
        title: '',
        challengeId: '',
        taskType: '',
        startTime: '',
        endTime: '',
        description: '',
        submissionTypes: {
          text: false,
          image: false,
          location: false
        },
        imageRequirements: {
          minCount: 1,
          maxCount: 5
        },
        textRequirements: {
          minLength: 10,
          maxLength: 500
        },
        reviewType: 'auto',
        points: 0,
        extraReward: '',
        extraRewardDetails: '',
        status: 'upcoming',
        priority: 3,
        settings: {
          featured: false,
          repeatable: false,
          requireVerification: false
        }
      },
      errors: {}
    }
  },
  created() {
    // 设置默认时间
    const today = new Date()
    this.formData.startTime = this.formatDateToISO(today)
    
    const endDate = new Date()
    endDate.setDate(today.getDate() + 7)
    this.formData.endTime = this.formatDateToISO(endDate)
    
    if (this.isEdit) {
      this.fetchTaskData()
    }
  },
  methods: {
    fetchTaskData() {
      this.loading = true
      this.error = null
      
      // 模拟API调用获取任务数据
      setTimeout(() => {
        // 在实际应用中，这里会调用API获取任务数据
        if (this.taskId === '1') {
          this.formData = {
            title: '每日骑自行车上班',
            challengeId: 1,
            taskType: 'daily',
            startTime: '2023-01-15',
            endTime: '2023-01-22',
            description: '放弃开车，选择骑自行车上班，减少碳排放。',
            submissionTypes: {
              text: true,
              image: true,
              location: false
            },
            imageRequirements: {
              minCount: 1,
              maxCount: 3
            },
            textRequirements: {
              minLength: 20,
              maxLength: 300
            },
            reviewType: 'manual',
            points: 30,
            extraReward: '',
            extraRewardDetails: '',
            status: 'completed',
            priority: 4,
            settings: {
              featured: true,
              repeatable: true,
              requireVerification: false
            }
          }
          this.loading = false
        } else {
          this.error = '未找到该任务数据'
          this.loading = false
        }
      }, 1000)
    },
    formatDateToISO(date) {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    },
    getPriorityText(priority) {
      const priorityMap = {
        1: '最低',
        2: '较低',
        3: '中等',
        4: '较高',
        5: '最高'
      }
      return priorityMap[priority] || '未知'
    },
    validate() {
      this.errors = {}
      
      // 基本信息验证
      if (!this.formData.title) {
        this.errors.title = '请输入任务名称'
      }
      
      if (!this.formData.challengeId) {
        this.errors.challengeId = '请选择所属挑战'
      }
      
      if (!this.formData.taskType) {
        this.errors.taskType = '请选择完成类型'
      }
      
      if (!this.formData.startTime) {
        this.errors.startTime = '请选择开始时间'
      }
      
      if (!this.formData.endTime) {
        this.errors.endTime = '请选择结束时间'
      } else if (this.formData.startTime && new Date(this.formData.endTime) <= new Date(this.formData.startTime)) {
        this.errors.endTime = '结束时间必须晚于开始时间'
      }
      
      if (!this.formData.description) {
        this.errors.description = '请输入任务描述'
      }
      
      // 提交方式验证
      if (!this.formData.submissionTypes.text && !this.formData.submissionTypes.image && !this.formData.submissionTypes.location) {
        this.errors.submissionTypes = '请至少选择一种提交方式'
      }
      
      // 积分验证
      if (typeof this.formData.points !== 'number' || this.formData.points < 0) {
        this.errors.points = '积分奖励必须是大于等于0的数字'
      }
      
      return Object.keys(this.errors).length === 0
    },
    goBack() {
      this.$router.push('/admin/tasks')
    },
    saveTask() {
      if (!this.validate()) {
        // 滚动到第一个错误
        this.$nextTick(() => {
          const firstError = document.querySelector('.admin-form-error')
          if (firstError) {
            firstError.scrollIntoView({ behavior: 'smooth', block: 'center' })
          }
        })
        return
      }
      
      this.loading = true
      
      // 模拟API保存
      setTimeout(() => {
        alert(this.isEdit ? '任务更新成功！' : '任务创建成功！')
        this.loading = false
        this.goBack()
      }, 1000)
    },
    confirmDeleteTask() {
      if (confirm(`确定要删除任务"${this.formData.title}"吗？此操作不可恢复！`)) {
        this.loading = true
        
        // 模拟API删除
        setTimeout(() => {
          alert('任务已删除')
          this.loading = false
          this.goBack()
        }, 1000)
      }
    }
  }
}
</script>

<style scoped>
.admin-task-edit {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 8px;
}

.loading-container,
.error-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 48px 0;
  background-color: white;
  border-radius: 4px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #1890ff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.error-icon {
  font-size: 48px;
  margin-bottom: 16px;
  color: #ff4d4f;
}

.edit-form-container {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.edit-form {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.form-section {
  padding: 24px;
  background-color: white;
  border-radius: 4px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.section-title {
  margin-top: 0;
  margin-bottom: 24px;
  font-size: 18px;
  color: rgba(0, 0, 0, 0.85);
  padding-bottom: 12px;
  border-bottom: 1px solid #f0f0f0;
}

.form-row {
  margin-bottom: 24px;
}

.form-row:last-child {
  margin-bottom: 0;
}

.form-row.two-col {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 24px;
}

.admin-form-label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: rgba(0, 0, 0, 0.85);
}

.admin-form-label.required::after {
  content: '*';
  color: #ff4d4f;
  margin-left: 4px;
}

.admin-form-helper {
  margin-top: 4px;
  font-size: 12px;
  color: rgba(0, 0, 0, 0.45);
}

.disabled-message {
  margin-top: 4px;
  font-size: 14px;
  color: rgba(0, 0, 0, 0.45);
  font-style: italic;
}

.small-input {
  width: 100px;
}

/* 提交方式设置 */
.submission-types {
  display: flex;
  gap: 24px;
}

.submission-type {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.submission-type input {
  margin-right: 8px;
}

/* 图片和文字要求 */
.image-requirements,
.text-requirements {
  display: flex;
  gap: 24px;
  align-items: center;
}

.req-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 审核规则 */
.review-options {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.review-option {
  display: flex;
  align-items: flex-start;
  cursor: pointer;
  padding: 12px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  transition: all 0.3s;
}

.review-option:hover {
  border-color: #40a9ff;
}

.review-option input {
  margin-top: 3px;
  margin-right: 12px;
}

.option-info {
  display: flex;
  flex-direction: column;
}

.option-title {
  font-weight: 500;
  margin-bottom: 4px;
}

.option-desc {
  font-size: 14px;
  color: rgba(0, 0, 0, 0.45);
}

/* 状态选项 */
.status-options {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.status-option {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.status-option input {
  margin-right: 8px;
}

/* 优先级滑块 */
.priority-slider {
  width: 100%;
  margin-bottom: 8px;
}

.slider {
  -webkit-appearance: none;
  width: 100%;
  height: 6px;
  border-radius: 3px;
  background: #f0f0f0;
  outline: none;
}

.slider::-webkit-slider-thumb {
  -webkit-appearance: none;
  appearance: none;
  width: 18px;
  height: 18px;
  border-radius: 50%;
  background: #1890ff;
  cursor: pointer;
  transition: all 0.3s;
}

.slider::-moz-range-thumb {
  width: 18px;
  height: 18px;
  border-radius: 50%;
  background: #1890ff;
  cursor: pointer;
  transition: all 0.3s;
}

.priority-labels {
  display: flex;
  justify-content: space-between;
  margin-top: 8px;
  color: rgba(0, 0, 0, 0.45);
  font-size: 14px;
}

.priority-value {
  margin-top: 8px;
  font-weight: 500;
  color: #1890ff;
}

/* 其他设置 */
.other-settings {
  display: flex;
  flex-wrap: wrap;
  gap: 24px;
}

.setting-item {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.setting-item input {
  margin-right: 8px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 16px;
  margin-top: 24px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .form-row.two-col {
    grid-template-columns: 1fr;
    gap: 16px;
  }
  
  .image-requirements,
  .text-requirements {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .submission-types {
    flex-direction: column;
    gap: 12px;
  }
  
  .form-actions {
    flex-wrap: wrap;
    justify-content: center;
  }
}
</style> 